package com.magic.cd.web.controller;

import java.io.InputStream;

import com.jfinal.core.ActionKey;
import com.jfinal.core.Controller;
import com.magic.cd.core.WeixinHandler;
import com.magic.cd.entry.ReceiveMessageVO;
import com.magic.cd.entry.ReceiveSignVO;
import com.magic.cd.util.MessageUtils;
import com.magic.cd.util.SignUtils;
import com.magic.cd.util.WeixinUtils;

/**
 * 微信控制器集
 * @author 	LiXing
 * @date	2016/5/6
 * */
@SuppressWarnings("deprecation")
public class WeixinController extends Controller{
	
	/**
	 * 微信控制器
	 * URL=http://www.xxx.com/weixin?sign=123&name=2313
	 * */
	@ActionKey("/weixin")
	public void weixin(){
		ReceiveSignVO sign = SignUtils.convert(this.getParaMap(), ReceiveSignVO.class);
		System.out.println(sign);
		try {
        	boolean signs = SignUtils.checkSignature(sign); 	//签名验证
        	if(signs){
        		if(sign.getEchostr()!=null){
        			//随机数不为空时，表示正在更换URL配置，直接返回该随机数
        			//一般只在更换URL配置时才会产生随机数，可放心返回
        			renderHtml(sign.getEchostr());
        		}else{
        			//处理正常的业务
        			InputStream in = this.getRequest().getInputStream();
        			ReceiveMessageVO msg = MessageUtils.parseXML(in, ReceiveMessageVO.class);
        			msg.setRealPath(this.getRequest().getRealPath("/"));
        			
        			System.out.println("msg:"+msg);
        			//----------------消息的响应逻辑----------------
        			String sendMessage = new WeixinHandler().run(msg);
        			renderHtml(sendMessage);
        		}
        	}
		} catch (Exception e) {
			renderHtml("error");
		}
	}
	
	/**
	 * 测试创建菜单
	 * URL=http://www.xxx.com/create/menu?data={"button":[{"name":"精彩东华"},{"name":"联系我们",{"sub_button":["type":"view":"name"]}}]}
	 * */
	@ActionKey("/create/menu")
	public void menu(){
		String data = this.getPara("data");
		data = data.replaceAll(" ", "");
		
		System.out.println("data:"+data);
		boolean res = WeixinUtils.createMeun(data);
		renderText(res?"创建成功":"创建失败，请检查传递的菜单是否符合规定格式！");
	}
}
